import type { MockMethod } from 'vite-plugin-mock';

// 模拟用户数据
export const mockConfigs = [
  {
    id: '1',
    username: 'admin',
    password: 'admin123',
    role: 'admin',
    name: '管理员'
  },
  {
    id: '2',
    username: 'user',
    password: 'user123',
    role: 'user',
    name: '普通用户'
  }
];

export const configApiMock: MockMethod[] = [
  {
    url: '/api/login',
    method: 'post',
    response: (request: any) => {
      const { username, password } = request.body;
      const user = mockConfigs.find(
        (u: any) => u.username === username && u.password === password
      );
      
      if (user) {
        return {
          code: 200,
          message: '登录成功',
          data: {
            id: user.id,
            username: user.username,
            role: user.role,
            name: user.name,
            token: `token_${user.id}_${Date.now()}`
          }
        };
      } else {
        return {
          code: 401,
          message: '用户名或密码错误'
        };
      }
    }
  },
  {
    url: '/api/user/info',
    method: 'get',
    response: (request: any) => {
      // 从请求头中获取token
      const token = request.headers.authorization?.split(' ')[1];
      if (token) {
        // 简单解析token获取用户id
        const userId = token.split('_')[1];
        const user = mockConfigs.find((u: any) => u.id === userId);
        if (user) {
          return {
            code: 200,
            message: '获取用户信息成功',
            data: {
              id: user.id,
              username: user.username,
              role: user.role,
              name: user.name
            }
          };
        }
      }
      return {
        code: 401,
        message: '未授权'
      };
    }
  },
  {
    url: '/api/logout',
    method: 'post',
    response: () => {
      return {
        code: 200,
        message: '退出登录成功'
      };
    }
  }
];

// 导出默认mock数据
export default configApiMock;